/*
 * Copyright (c) 2022 Institute of Software Chinese Academy of Sciences (ISCAS)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package space.ao.services.auth.repository;

import io.quarkus.hibernate.orm.panache.PanacheRepository;

import jakarta.inject.Singleton;
import jakarta.transaction.Transactional;

import space.ao.services.auth.entity.TotpEntity;

import java.time.OffsetDateTime;
import java.util.Optional;

@Singleton
public class TotpRepository implements PanacheRepository<TotpEntity> {
  public Optional<TotpEntity> findByUserid(Long userid) {
    return find("userid", userid).firstResultOptional();
  }

  @Transactional
  public void insertOrUpdate(Long userid, String totpSecret) {
    var totpEntity = this.findByUserid(userid);
    if (totpEntity.isEmpty()) {
      var newTotpEntity = new TotpEntity();
      newTotpEntity.setUserid(userid);
      newTotpEntity.setTotpSecret(totpSecret);
      newTotpEntity.setCreateAt(OffsetDateTime.now());
      newTotpEntity.setAuthenticator(false);
      this.persist(newTotpEntity);
    } else {
      this.update("totpSecret = ?1, createAt = ?2 where userid = ?3", totpSecret, OffsetDateTime.now(), userid);
    }
  }

  @Transactional
  public void setAuthenticatorStatus(long userId, boolean status) {
    this.update("authenticator = ?1 where userid = ?2", status, userId);
  }

}
